import React, { useState, useEffect } from 'react'
import { SortableContainer, SortableElement } from 'react-sortable-hoc'
import Actions from './Actions'
const SortableBox = SortableElement(({ children }: any) => (
  <div>{children}</div>
))

const SortableWrapper = SortableContainer(({ children }) => (
  <div>{children}</div>
))

function DraggableBox({ children, onSortEnd, useWindowAsScrollContainer }) {
  const [show, setShow] = useState(false)

  useEffect(() => {
    setShow(true)
  }, [])

  if (!show) {
    return null
  }

  return (
    <SortableWrapper
      onSortEnd={onSortEnd}
      useWindowAsScrollContainer={useWindowAsScrollContainer}
    >
      <SortableBox>{children}</SortableBox>
    </SortableWrapper>
  )
}

function App() {
  const [items, setItems] = useState([1, 2, 3])

  const onSortEnd = ({ oldIndex, newIndex }) => {
    setItems(arrayMove(items, oldIndex, newIndex))
  }

  const handleClick = () => {
    console.log('2222')
  }

  return (
    <div>
      {items.map((item) => {
        return (
          <DraggableBox onSortEnd={onSortEnd} useWindowAsScrollContainer={true}>
            <>
              <div>
                <h1>Content</h1>
                <div
                  onClick={() => {
                    console.log('222')
                  }}
                  style={{ cursor: 'pointer' }}
                >
                  This is some content.
                </div>
              </div>
              <Actions onClick={handleClick} />
            </>
          </DraggableBox>
        )
      })}
    </div>
  )
}

function arrayMove(arr, oldIndex, newIndex) {
  if (newIndex >= arr.length) {
    var k = newIndex - arr.length + 1
    while (k--) {
      arr.push(undefined)
    }
  }
  arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0])
  return arr
}

export default App
